#define _DEFAULT_SOURCE
#include "app_runner.h"
#include <stdlib.h>
#include <signal.h>
#include "app_pool.h"
#include "app_serial.h"
#include "app_router.h"
#include "log/log.h"

static int is_running = 1;

static void app_runner_signalHandler (int signum)
{
    if (signum == SIGTERM || signum == SIGINT)
    {
        log_warn("Received signal %d, shutting down", signum);
        is_running = 0;
    }
}

void app_runner_run()
{
    signal(SIGTERM, app_runner_signalHandler);
    signal(SIGINT, app_runner_signalHandler);

    SerialDevice *device = app_serial_init("/dev/ttyS2",BAUD_115200);
    if (device == NULL)
    {
        log_warn("Failed to initialize serial device");
        return -1;
    }
    if (app_serial_setConnectionType(device, CONN_BT) != 0)
    {
        log_warn("Failed to set connection type");
        return -1;
    }
    if (app_router_init() != 0)
    {
        log_warn("Failed to initialize app router");
        return -1;
    }
    if (app_router_registerDevice(&device->super) != 0)
    {
        log_warn("Failed to register device");
        return -1;
    }
    if (app_pool_init(5) != 0)
    {
        log_warn("Failed to initialize app pool");
        return -1;
    }

    while (is_running)
    {
        usleep(100000); // 休眠100ms
    }

    app_router_close();
    app_pool_close();

    return 0;
}